package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.servcie.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.Request;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 登录
     * @param employee
     * @param request
     * @return
     */
    @PostMapping("/login")
    private R<Employee> login(@RequestBody Employee employee, HttpServletRequest request){
        String username = employee.getUsername();
        String password = employee.getPassword();
        //1.密码加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //2.核对用户名
        LambdaQueryWrapper<Employee> wrapper= new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername,username);
        Employee emp = employeeService.getOne(wrapper);
        if (!(emp.getUsername().equals(username))){
            return  R.error("用户名和密码不匹配");
        }
        //3.密码用户名
        if (!(emp.getPassword().equals(password))){
            return  R.error("用户名和密码不匹配");
        }
        //4.用户名状态是否正常
        if (emp.getStatus()==0){
            return  R.error("用户名和密码不匹配");
        }

        //补充: 把用户ID存到session中
        request.getSession().setAttribute("employee",emp.getId());
        //5.登录成功
        return R.success(emp);
    }

    /**
     * 退出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    private R<String> login( HttpServletRequest request){
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

}
